<?php
namespace app\admin\controller;


use app\common\logic\Users;
use app\common\model\Band;
use app\common\model\Check;
use app\common\model\LoginLog;
use app\common\model\MoneyDetail;
use app\common\model\MyPackage;
use think\Db;
use think\Exception;
use think\Loader;


class User extends Base
{

    function _initialize()
    {
        parent::_initialize();
        $this->assign('stamp',123);
    }

    public function index()
    {
        $where = [];
        if(!empty($_GET['nick_name'])){
            $where['a.nick_name|a.phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }

        if(!empty($_GET['user_id'])){
            $where['a.user_id'] = trim(input('get.user_id'));
        }

        if (is_numeric(input('status'))){
            $where['a.status'] = input('status');
        }

        if (is_numeric(input('sex'))){
            $where['a.sex'] = input('sex');
        }

        if(!empty($_GET['start'])&&empty($_GET['end'])){
            $where['a.create_time'] = ['>=',strtotime($_GET['start'])];
        }elseif(!empty($_GET['end'])&&empty($_GET['start'])){
            $where['a.create_time'] = ['<=',strtotime($_GET['end'])];
        }elseif(!empty($_GET['start'])&&!empty($_GET['end'])){
            $where['a.create_time'] = ['between',array(strtotime($_GET['start']),strtotime($_GET['end']))];
        }

        if (is_numeric(input('level'))){
            $where['e.level'] = input('level');
        }

        $model = new \app\common\model\Users();
        $money = $model->cache(300)->sum('money');
        $cash  = $model->cache(300)->sum('cash');
        $rows = $model->userList($where);
        $this->assign([
            'title' => '用户管理',
            'rows' => $rows,
            'money' => $money,
            'cash' => $cash,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }


    /**
     * @return \think\response\View
     * 用户信息编辑
     */
    public function user_edit()
    {
        if(request()->isPost()){
            $data  = input('post.');
            $model = new Users();
            if (!empty($data['phone'])){
                $phone = Db::name('users')
                    ->where('phone',$data['phone'])
                    ->where('user_id','<>',$data['id'])
                    ->value('user_id');
                if ($phone){
                    $this->error('该手机号已注册');
                }
            }
            if (!empty($data['phone'])){
                $phone = Db::name('users')
                    ->where('uuid',$data['uuid'])
                    ->where('user_id','<>',$data['id'])
                    ->value('user_id');
                if ($phone){
                    $this->error('该账号已存在');
                }
            }
            if ($data['id']){
                $map['user_id'] = $data['id'];
                $map['type']    = 6;
                MyPackage::where($map)->update(['num'=>$data['box6']]);
                $map['type']    = 5;
                MyPackage::where($map)->update(['num'=>$data['box5']]);
                $map['type']    = 4;
                MyPackage::where($map)->update(['num'=>$data['box4']]);
            }

            $result = $model->saveChange($data);
            if($result){
                $this->success('操作成功');
            }
            $this->error($model->getError());
        }
        $isTest = false;
        if (is_numeric(input('id'))){

            //测试服地址
            if (request()->domain() == config('alphaUrl')){
                $isTest = true;

            }

            $map['p.user_id'] = input('id');

            $map['p.type'] = ['in',[4,5,6]];

            $box  = array_key(MyPackage::getRows($map),'type');
            $this->assign([
                'box' => $box,
            ]);


        }
        $this->_show('users','user_id');
        $this->assign([
            'title' => '用户信息编辑',
            'isTest' => $isTest,
        ]);
        return view();
    }

    public function change()
    {
        $data = input();
        $result = Db::name('users')->update(['status'=>$data['type'],'user_id'=>$data['id']]);
        if($result !== false){
            \app\api\controller\Base::outRoomFunc($data['id'],\app\api\controller\Base::staticInfo('room_id',$data['id']));
            //改变用户状态后清空前端token
            cache('token_'.hashid($data['id']),null);
            if ($data['type'] == 0){

                //封禁用户发送封禁消息
                $this->banedUser($data['id'],$data['end_time']);
            }

            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    public function user_pass()
    {
        $id     = input('param.id');
        $result = Db::name('users')->where('user_id',$id)->delete();
        if ($result){
            \app\api\controller\Base::outRoomFunc($id,\app\api\controller\Base::staticInfo('room_id',$id));
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }


    public function band()
    {
        $IMEI = input('IMEI');
        $user_id = input('user_id');
        $id = Db::name('band')->where('IMEI',$IMEI)->value('id');
        if ($id){
            $this->error('设备已被封禁');
        }
        $data['IMEI'] = $IMEI;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $result = Band::insert($data);
        if ($result !== false){
            cache('token_'.hashid($user_id),null);
            \app\api\controller\Base::outRoomFunc($user_id,\app\api\controller\Base::staticInfo('room_id',$user_id));
            $this->banedUser($user_id);
            $this->success('封禁成功');
        }
        $this->error('封禁失败');
    }


    public function band_list()
    {
        $where = [];

        if(!empty($_GET['IMEI'])){
            $where['a.IMEI'] = input('get.IMEI');
        }

        $model = new Band();
        $rows = $model->getList($where);
        $this->assign([
            'title' => '封禁设备列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }


    public function band_del()
    {
        $this->_del('band');
    }



    /**
     * 登陆日志列表
     */
    public function log()
    {
        $where = [];
        if(!empty($_GET['nick_name'])){
            $where['c.nick_name|c.phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }

        if(!empty($_GET['ip'])){
            $where['b.ip'] = input('get.ip');
        }
        if(!empty($_GET['IMEI'])){
            $where['b.IMEI'] = input('get.IMEI');
        }
        $model = new LoginLog();
        $rows = $model->getList($where);
        $this->assign([
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }

    public function del()
    {
        $id     = input('param.id');
        $result = Db::name('login_log')->delete($id);
        if ($result){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    public function cate()
    {
        $this->_list2('users_category','create_time DESC');
        $this->assign([
            'title'=>'用户类型'
        ]);
        return view();
    }

    public function cate_edit()
    {
        if (request()->isPost()){
            $data   = input('post.');
            $result = Db::name('users_category')->strict(false)->where('cid',$data['id'])->update($data);
            if($result!==false){
                $this->success('保存成功','/user/cate');
            }
            $this->error('操作失败');
        }
        $this->_show('users_category','cid');
        return view();
    }



    /**
     * 用户资金明细列表
     */
    public function detail()
    {



        $id = $this->request->param('id');
        $where = [];
        if (is_numeric($id)){
            $where['a.user_id'] = $id;
        }

        if (input('keyword')){
            $where['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
        }

        if (is_numeric(input('type'))){
            $where['a.type'] = input('type');
        }

        if (is_numeric(input('keyword'))){
            $where['a.remark'] = ['like','%'.trim(input('keyword')).'%'];
        }

        $where['a.status'] = 1;
        if(!empty($_GET['start'])&&empty($_GET['end'])){
            $where['a.create_time'] = ['>=',strtotime($_GET['start'])];
        }elseif(!empty($_GET['end'])&&empty($_GET['start'])){
            $where['a.create_time'] = ['<=',strtotime($_GET['end'])];
        }elseif(!empty($_GET['start'])&&!empty($_GET['end'])){
            $where['a.create_time'] = ['between',array(strtotime($_GET['start']),strtotime($_GET['end']))];
        }


        $model = new MoneyDetail();

        if (input('download') == 'download'){ //点击了下载
            /* 永不超时 */
            ini_set('max_execution_time', 0);
            $rows = $model->downloadList($where);
            //         $path = ROOT_PATH.'public'.DS.'download'.DS.'excel'; //找到当前脚本所在路径
            Loader::import('PHPExcel.PHPExcel');//手动引入PHPExcel.php
//         Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');//引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
            $PHPExcel = new \PHPExcel();//实例化
            $PHPSheet = $PHPExcel->getActiveSheet();
            $PHPSheet->setTitle("资金明细".date('Ymdhis')); //给当前活动sheet设置名称
            $PHPSheet->setCellValue("A1","id")//表格数据
            ->setCellValue("B1","用户昵称")
                ->setCellValue("C1","类型")
                ->setCellValue("D1","金额")
                ->setCellValue("E1","详情")
                ->setCellValue("F1","备注")
                ->setCellValue("G1","日期");
            if (empty($rows)) $this->error('暂无数据');
            $i = 1;
            foreach ($rows as $k => $v){
                $i++;
                $PHPSheet->setCellValue("A$i",$v['d_id'])
                    ->setCellValue("B$i",$v['nick_name'])
                    ->setCellValue("C$i",$v['type'] == 1 ? '收入': '支出')
                    ->setCellValue("D$i",$v['money'])
                    ->setCellValue("E$i",$v['title'])
                    ->setCellValue("F$i",$v['remark'])
                    ->setCellValue("G$i",$v['create_time']);
            }
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");//创建生成的格式
            $date = date('Ymdhis');
            header('Content-Disposition: attachment;filename="资金明细'.$date.'.xlsx"');//下载下来的表格名
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
            exit;

        }

        $rows = $model->money_detail_list($where);
        $this->assign([
            'title' => '资金明细',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view('money_detail');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 发送极光推送
     */
    public function push()
    {
        if (request()->isPost()){
            $data = input('post.');
            $push_id = 'all';
            if (is_numeric($data['user_id'])){
                $push_id = Db::name('user_extend')->where('user_id',$data['user_id'])->value('j_push_id');
                if (empty($push_id)) $this->error('推送失败,用户无推送id');
            }
            $result = j_push($data['title'],$push_id);
            if ($result){
                $this->success('发布成功');
            }
        }
        $this->error('系统繁忙,请稍后重试');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 发送客服消息
     */
    public function customer()
    {
        if (request()->isPost()){
            $data = input('post.');
            $map['status'] = 1;
            if (is_numeric($data['user_id'])){
                $map['user_id'] = $data['user_id'];

            }
            $msg['url']   = $data['url'];
            $msg['img']   = $data['img'];
            $msg['title'] = $data['title'];
            Db::name('users')->where($map)->field('user_id')->chunk(1000,function ($users)use($msg){
                foreach($users as $user){
                    // 处理user模型对象
                    $userIds[] = hashid($user['user_id']);
                }

                \app\api\controller\Base::sendUsrMsg('sysCustomer',$userIds,$msg);

            });
            $this->success('发送成功',url('index'));
        }
        return view();
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改审核列表
     */
    public function check()
    {
        $model = new Check();
        $map   = [];
        if (input('nick_name')){
            $map['u.nick_name'] = ['like','%'.trim(input('nick_name')).'%'];
        }
        if (is_numeric('status')){
            $map['a.status'] = input('status');
        }
        $rows  = $model->getList($map);
        $this->assign([
            'title' => '修改审核列表',
            'pageHTML' => $rows->render(),
            'rows' => $rows,
        ]);
        return view();
    }

    /**
     * 审核批量操作
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function batch()
    {
        $ids = input('id/a');
        $type = input('type');
        switch ($type){
            case 'delete':
                $result = Check::destroy($ids);
                break;
            default:
                if ($type == 'success'){
                    //通过
                    $result = Check::where('check_id','in',$ids)->update(['status'=>1]);
                }else{
                    //回滚
                    foreach ($ids as $k => $id){
                        Db::startTrans();
                        try{
                            $info = Db::name('check')->where('check_id',$id)->findOrFail();
                            if ($info['status'] != 2){
                                continue;
                            }
                            switch ($info['type']){
                                case 1:
                                    Db::name('users')->where('user_id',$info['user_id'])->update(['header_img'=>$info['before']]);
                                    $str = sprintf('您于%s修改的头像因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                                    //发送系统消息
                                    \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                                    break;
                                case 2:
                                    if (!is_numeric($info['extend'])){
                                        $this->error('参数错误');
                                    }
                                    if (empty($info['before'])){
                                        Db::name('user_img')->where('img_id',$info['extend'])->delete();
                                        $str = sprintf('您于%s添加的形象照因不符合规范系统已删除',date('Y-m-d H:i',$info['create_time']));
                                        //发送系统消息
                                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                                    }else{
                                        Db::name('user_img')->where('img_id',$info['extend'])->update(['img'=>$info['before']]);
                                        $str = sprintf('您于%s修改的形象照因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                                        //发送系统消息
                                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                                    }
                                    break;
                                case 3:
                                    Db::name('users')->where('user_id',$info['user_id'])->update(['sign'=>$info['before']]);
                                    $str = sprintf('您于%s修改的昵称因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                                    //发送系统消息
                                    \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                                    break;
                                case 4:
                                    Db::name('users')->where('user_id',$info['user_id'])->update(['nick_name'=>$info['before']]);
                                    $str = sprintf('您于%s修改的昵称因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                                    //发送系统消息
                                    \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                                    break;
                            }
                            Db::name('check')->whereOr('check_id',$id)->update(['status'=>0]);
                        Db::commit();
                        }catch (Exception $e){
                            Db::rollback();
                            $this->error($e->getMessage());
                        }
                    }

                    $this->success('操作成功');
                }
                break;
        }
        if ($result !== false){
            $this->success('操作成功');
        }

        $this->error('操作失败');

    }

    public function edit()
    {
        $data = input();
        $info = Db::name('check')->where('check_id',$data['id'])->findOrFail();

        Db::startTrans();
        try{
            if ($data['status'] == 0){  //未通过审核  回滚数据
                switch ($info['type']){
                    case 1:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['header_img'=>$info['before']]);
                        $str = sprintf('您于%s修改的头像因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                    case 2:
                        if (!is_numeric($info['extend'])){
                            $this->error('参数错误');
                        }
                        if (empty($info['before'])){
                            Db::name('user_img')->where('img_id',$info['extend'])->delete();
                            $str = sprintf('您于%s添加的形象照因不符合规范系统已删除',date('Y-m-d H:i',$info['create_time']));
                            //发送系统消息
                            \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        }else{
                            Db::name('user_img')->where('img_id',$info['extend'])->update(['img'=>$info['before']]);
                            $str = sprintf('您于%s修改的形象照因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                            //发送系统消息
                            \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        }
                        break;
                    case 3:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['sign'=>$info['before']]);
                        $str = sprintf('您于%s修改的昵称因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                    case 4:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['nick_name'=>$info['before']]);
                        $str = sprintf('您于%s修改的昵称因不符合规范系统已撤回修改',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                }

            }

            Db::name('check')->whereOr('check_id',$data['id'])->update(['status'=>$data['status']]);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }
    
    
    
    public function delete()
    {
        $this->_del('check');
    }
    



}
